import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const files = require.context('./modules', false, /\.js$/)
const modules = {}

files.keys().forEach(key => {
  modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

export default new Vuex.Store({
  modules,
  state: {
    __prefix: '',
    __name: ''
  },
  actions: {
    __autoload(context) {
      this.$log = function (state, ...args) {
        this._vm.$log({ __module: 'store', __prefix: state.__prefix, __name: state.__name }, ...args)
      }

      console.log('[store][/] 初始化')

      Object.keys(modules).forEach(key => {
        if (!!modules[key]['actions'] && !!modules[key]['actions']['__autoload']) {
          context.dispatch(`${key}/__autoload`, context.state.__prefix + context.state.__name)
        }
      })

      console.log('store loaded success')
    }
  }
})
